import _ from 'lodash';
import { TRMessage } from '@/components';

export const POWER_ENUM = {
  POWER_COUNT: 'quantity',
  POWER_PRICE: 'price',
};

export const countTotal = (arr = []) => {
  if (_.isArray(arr)) {
    const sum = arr.reduce((pre, next) => pre + next[POWER_ENUM.POWER_COUNT] * 1, 0);
    const priceSum = arr.reduce(
      (pre, next) => pre + next[POWER_ENUM.POWER_COUNT] * next[POWER_ENUM.POWER_PRICE],
      0,
    );
    return { sum, priceSum };
  }
};

export const initTimeEnum = () => {
  return Array.from({ length: 96 }).map((i, k) => {
    let value = getKHead(k + 1);
    const arr = value.split('');
    arr.splice(2, 0, ':');
    value = arr.join('');
    return value;
  });
};

// 根据index来获取24点的字符串
export const getKHead = (index) => {
  const value = Math.floor(index / 4);
  const residue = index % 4;
  let num = (value * 100 + residue * 15).toString();
  num = num.padStart(4, '0');
  return num;
};

// 在24点字符串中添加:
export const getPoints = (arr) => {
  const obj = {};
  arr.forEach((i) => {
    const arr = i.key.split('');
    arr.splice(2, 0, ':');
    const key = arr.join('');
    obj[key] = i.value;
  });
  return obj;
};

// 将array转换为object
export const arrToObj = (arr) => {
  const obj = {};
  if (_.isArray(arr)) {
    arr.map((i) => {
      obj[i.id] = i;
    });
  }
  return obj;
};

// 将object转换为array
export const objToArr = (obj) => {
  const arr = [];
  if (_.isObject(obj)) {
    for (let key in obj) {
      arr.push({ ...obj[key], index: arr.length + 1 });
    }
  }
  return arr;
};

// 获取可以使用的id
export const getAccessId = (obj) => {
  const keys = Object.keys(obj);
  if (keys.length === 0) {
    return 1;
  } else {
    const lastKey = keys.pop();
    return Number(lastKey) + 1;
  }
};

// 判断是否所有行都选择了时间段
export const judgeIsTime = (arr = [], showMes = true) => {
  if (arr.length === 0) {
    showMes && TRMessage.error('请至少添加一行数据!');
    return false;
  }
  let errLine = [];
  arr.forEach((i, k) => {
    if (i.startTime === null || i.endTime === null) {
      errLine.push(k + 1);
    }
  });
  if (errLine.length !== 0) {
    showMes && TRMessage.error(errLine.toString() + '行请选择时间段!');
    return false;
  } else {
    return true;
  }
};

// 获取所有场站
export const getStationList = (arr = []) => {
  const value = [];
  const ids = [];
  arr.forEach((i) => {
    if (i?.children instanceof Array) {
      i.children.forEach((v) => {
        value.push({ ...v, label: v.stationName, value: v.stationId });
        ids.push(v?.stationId);
      });
    }
  });
  return { value, ids };
};

// 构建新增合约所需要的参数
export const buildAddResult = (arr) => {
  const TIME_ENUM = initTimeEnum();
  return arr?.map((i) => {
    delete i.index;
    delete i.showTimePicker;
    delete i.quantityChecked;
    delete i.priceChecked;
    return {
      ...i,
      endTime: TIME_ENUM[i.endTime],
      startTime: TIME_ENUM[i.startTime],
    };
  });
};
